package com.ts.common.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ts.common.security.dto.UserToken;

import java.util.Date;

public class JWTUtils {

    private static String sign = "Java2302";

    public static String creatToken(String json) {
        return JWT.create().withClaim("userInfo", json).sign(Algorithm.HMAC256(sign));
    }
    public static String createUserToken(UserToken userToken,Long expireTime) {
        Date now = new Date();
        userToken.setCreateTime(now);
        userToken.setExpireTime(new Date(now.getTime()+expireTime));
        return JWT.create().withClaim("userInfo", JSON.toJSONString(userToken)).sign(Algorithm.HMAC256(sign));
    }

    public static Boolean checkToken(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static String getUserInfo(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
        return verify.getClaim("userInfo").asString();
    }
}
